﻿using System;
using System.Threading.Tasks;
using Thinker.SignChannel.Entities;
using Thinker.SignChannel.Repositories;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Uow;

namespace Thinker.SignChannel.Results;

public class ResultBuilder(
    IPersonTimeRepository personTimeRepository,
    ResultCalculatorFactory calculatorFactory,
    PersonTimeCreator personTimeCreator) : ITransientDependency
{
    [UnitOfWork]
    public async Task CalcAllAsync(Guid timeId)
    {
        await personTimeCreator.BuildAllAsync(timeId);
        var personTimes = await personTimeRepository.GetListAsync();
        foreach (var personTime in personTimes)
        {
            await UpdateAsync(personTime);
        }

        await personTimeRepository.UpdateManyAsync(personTimes);
    }

    [UnitOfWork]
    public virtual async Task BuildAsync(PersonTime personTime)
    {
        await UpdateAsync(personTime);
        await personTimeRepository.UpdateAsync(personTime, true);
    }

    public async Task UpdateAsync(PersonTime personTime)
    {
        var result = await calculatorFactory.CalcAsync(personTime);
        personTime.SignResult = result.Result;
        personTime.RecordId = result.Record?.Id;
    }
}